package com.madou.dbtool.redis.panel.ui;

import com.madou.common.annotation.HideClass;
import com.madou.dbtool.common.messages.DBToolBundle;
import com.madou.dbtool.redis.manager.RedisSourceManager;
import com.madou.dbtool.redis.panel.converter.ListToCommandCellDataConverter;
import com.madou.dbtool.redis.panel.dataloader.RedisSlowLogTableDataLoader;
import com.madou.dbtool.ui.table.MColumn;
import com.madou.dbtool.ui.table.MTable;
import com.madou.dbtool.ui.table.enums.DataType;
import com.madou.dbtool.ui.table.row.MObjectRow;
import redis.clients.jedis.resps.Slowlog;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

/**
 * @author miukoo
 * redis慢日志面板
 */
@HideClass
public class RedisSlowLogPanel extends JPanel {
    private final static String TIME_GET = "config get slowlog-log-slower-than";
    private final static String TIME_SET = "config set slowlog-log-slower-than ";
    private final static String LENGTH_GET = "config get slowlog-max-len";
    private final static String LENGTH_SET = "config set slowlog-max-len ";
    private JPanel panel;
    private JCheckBox autoRefreshCheckBox;
    private JSpinner sloweTime;
    private JSpinner slowLength;
    private MTable table;
    private JButton clearButton;
    private JScrollPane scrollPane;
    private static List<MColumn> columns = new ArrayList<>();
    private RedisSlowLogTableDataLoader dataLoader;
    RedisSourceManager redisSourceManager;
    // 自动刷新线程
    Thread refresh;

    static {
        MColumn unique = new MColumn();
        unique.setName("id");
        unique.setTitle("ID");
        unique.setCanEdit(false);
        columns.add(unique);

        MColumn date = new MColumn();
        date.setDataType(DataType.TIMESTAMP_10);
        date.setName("timeStamp");
        date.setCanEdit(false);
        date.setTitle(DBToolBundle.message("redis.slow.log.panel.table.col.date"));
        columns.add(date);

        MColumn command = new MColumn();
        command.setName("args");
        command.setConverter(new ListToCommandCellDataConverter());
        command.setTitle(DBToolBundle.message("redis.slow.log.panel.table.col.command"));
        columns.add(command);
    }

    public RedisSlowLogPanel(RedisSourceManager redisSourceManager){
        this.redisSourceManager = redisSourceManager;
    }

    /**
     * 初始化组件
     */
    private void createUIComponents() {
        table = new MTable(columns,new RedisSlowLogTableDataLoader(redisSourceManager));
    }

    /**
     * 初始化布局
     */
    public void init(){
        this.setLayout(new BorderLayout());
        this.add(panel,BorderLayout.CENTER);
        this.initEvent();
        loadData();
        Color color = UIManager.getColor("EditorPane.background");
        if (color == null) {
            color = Color.WHITE;
        }
        scrollPane.getViewport().setBackground(color);
        scrollPane.setBackground(color);
        table.setBackground(color);
    }

    /**
     * 初始化事件
     */
    private void initEvent(){
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                redisSourceManager.execute(-1,"SLOWLOG RESET");
                loadData();
            }
        });
        sloweTime.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent changeEvent) {
                Long value = Long.valueOf(sloweTime.getValue().toString());
                if(value>=0) {
                    redisSourceManager.execute(-1,TIME_SET + value);
                }else{
                    sloweTime.setValue(0);
                }
            }
        });
        slowLength.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent changeEvent) {
                Long value = Long.valueOf(slowLength.getValue().toString());
                if(value>=0) {
                    redisSourceManager.execute(-1,LENGTH_SET + value);
                }else{
                    slowLength.setValue(0);
                }
            }
        });
        autoRefreshCheckBox.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent changeEvent) {
                if(autoRefreshCheckBox.isSelected()){
                    openAutoRefresh();
                }else{
                    closeAutoRefresh();
                }
            }
        });
    }

    /**
     * 加载面板数据
     */
    private void loadData(){
        sloweTime.setValue(getData(TIME_GET));
        slowLength.setValue(getData(LENGTH_GET));
        table.setPageSize(Integer.valueOf(slowLength.getValue().toString()));
        try {
            table.load();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数字内容
     * @param command
     * @return
     */
    private long getData(String command){
        try {
            Object execute = redisSourceManager.execute(-1,command);
            if (execute instanceof ArrayList) {
                ArrayList<byte[]> list = (ArrayList<byte[]>) execute;
                if (list.size() == 2) {
                    return Long.valueOf(new String(list.get(1)));
                }
            }
        }catch (Exception e){

        }
        return 0;
    }

    /**
     * 开启自动刷新
     */
    public void openAutoRefresh(){
        if(refresh==null){
            refresh = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true&&!Thread.currentThread().isInterrupted()){
                        try {
                            Thread.sleep(5_000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        loadData();
                    }
                }
            });
            refresh.start();
        }
    }

    /**
     * 关闭自动刷新
     */
    public void closeAutoRefresh(){
        if(refresh!=null){
            refresh.interrupt();
            refresh.stop();
            refresh = null;
        }
    }

    public RedisSourceManager getRedisSourceManager() {
        return redisSourceManager;
    }
}
